/**
 * 岗位授权申请详情
 */
<template>
    <el-form v-loading="loading" :model="formData" :rules="currentFormPostApplys" ref="formRef" label-width="140px" :scroll-to-error="true">
        <vp-card>
            <template #header>
                <vp-label zh="基本信息" en="Basic Info" />
            </template>
            <el-row>
                <vp-col :span="4">
                    <el-form-item prop="bh">
                        <template #label><vp-label zh="记录单号" en="Record No." align="left" /></template>
                        <el-input v-model="formData.bh" v-if="type == 'add' || type == 'edit' || type == 'revision'" v-trim disabled placeholder="无需填写,由系统自动生成"
                            maxlength="100">
                        </el-input>
                        <span v-else>{{ formData.bh }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="sqrdaid">
                        <template #label><vp-label zh="申请人编号" en="Applicant No."/></template>
                        <el-input readonly v-model="formData.sqrbh" v-if="type === 'add' || type === 'edit'">
                            <template #append>
                                <el-button @click="handleChooseTrainer"><SvgIcon name="ele-Search"/></el-button>
                            </template>
                        </el-input>
                        <span v-else>{{ formData.sqrbh }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="sqrxm">
                        <template #label><vp-label zh="申请人姓名" en="Applicant Name" align="left"/></template>
                        <el-link @click="handlePersonnelFileClick">
                            <span>{{ formData.sqrxm }}</span>
                        </el-link>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="sqrq">
                        <template #label><vp-label zh="申请日期" en="Application Date" align="left" /></template>
                        <el-date-picker v-if="type === 'add' || type === 'edit'" 
                        v-model="formData.sqrq" type="date" value-format="YYYY-MM-DD"></el-date-picker>
                        <span v-else>{{ formData.sqrq }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="4">
                    <el-form-item prop="sqlx">
                        <template #label><vp-label zh="类型" en="Type"/></template>
                        <el-select v-model="formData.sqlx" v-if="type === 'add' || type === 'edit' || type =='reedit'">
                            <el-option :value="10" label="初次申请/Init. App."></el-option>
                            <el-option :value="20" label="续签/Renewal"></el-option>
                            <el-option :value="30" label="增补/Supp. App."></el-option>
                        </el-select>
                        <span v-else>{{ formData.sqlx == 10 ? "初次申请/Init. App." : formData.sqlx == 20 ? '续签/Renewal' : 
                        formData.sqlx == 30 ? '增补/Supp. App.' :  "" }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="sqgwid">
                        <template #label><vp-label zh="授权岗位" en="Authorization Position" align="left" /></template>
                        <el-input v-model="formData.sqgwmc" readonly v-if="type === 'add' || type === 'edit'" >
                            <template #append>
                                <el-button @click="handleChoosePosition">
                                    <SvgIcon name="ele-Search" />
                                </el-button>
                            </template>
                        </el-input>
                        <span v-else>{{ formData.sqgwmc }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row v-if="type === 'add' || type === 'edit' || type =='reedit' || (formData.actypes && formData.actypes.length > 0)">
                <vp-col :span="1">
                    <el-form-item>
                        <template #label><vp-label zh="授权机型" en="Authorization AC Type" /></template>
                        <vp-vxe-table id="contactId" ref="tableRef" :data="formData.actypes" row-key="id"
                            maxHeight="300">
                            <vxe-column type="seq" align="center" title="#" width="50" />
                            <vxe-column field="jx">
                                <template #header><vp-label zh="机型" en="AC Type" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`actypes[${scope.rowIndex}].jx`" label-width="auto" :rules="formPostApplys.jx">
                                        <VpAircraftTypeSelect 
                                            v-if="type === 'add' || type === 'edit' || type =='reedit'"
                                            :selectedId="scope.row.jx" 
                                            :fjjx="true"
                                            class="w100"
                                            @selected="(obj:any) =>{scope.row.jx = obj.jx}"
                                        />
                                        <span v-else>{{ scope.row.jx }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="lb">
                                <template #header><vp-label zh="授权类型" en="Authorization Type" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`actypes[${scope.rowIndex}].lb`" label-width="auto">
                                        <el-input v-model="scope.row.lb" placeholder="请输入"  v-if="type === 'add' || type === 'edit' || type =='reedit'" />
                                        <span v-else>{{ scope.row.lb }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column align="center" width="100"  v-if="type === 'add' || type === 'edit' || type =='reedit'">
                                <template #header>
                                    <el-button circle @click="handleAddAcType()">
                                        <SvgIcon name="ele-Plus"></SvgIcon>
                                    </el-button>
                                </template>
                                <template #default="scope">
                                    <el-button circle @click="handleDeleteAcType(scope.rowIndex)">
                                        <SvgIcon name="ele-Minus"></SvgIcon>
                                    </el-button>
                                </template>
                            </vxe-column>
                        </vp-vxe-table>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="1">
                    <el-form-item prop="bz">
                        <template #label><vp-label zh="备注" en="Remark"/></template>
                        <el-input 
                            type="textarea" 
                            v-model="formData.bz" 
                            maxlength="1000" 
                            :autosize="{ minRows: 4}"
                            v-if="isEditPage"
                        >
                        </el-input>
                        <span v-else style="white-space:pre">{{ formData.bz }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
        </vp-card>
        <vp-card v-if="type === 'training' || type === 'quality' || type === 'audit' || (type === 'view' && formData.trainings.length && formData.trainings[0].pgjg)">
            <template #header>
                <vp-label zh="培训评估" en="Training Evaluation" />
            </template>
            <el-row>
                <vp-col :span="1">
                    <el-form-item>
                        <template #label>
                            <div>
                                <div> <vp-label zh="培训要求" en="Training Requirements" /> </div>
                                <div style="margin-top: 10px;">
                                    <vp-label zh="重新加载" en="Reload" style="cursor: pointer;" @click="loadTrainingList" v-if="type == 'training'" />
                                </div>
                            </div>
                        </template>
                        <vp-vxe-table id="contactId" ref="tableRef" :data="formData.trainings" row-key="id"
                            maxHeight="300" v-loading="loading1">
                            <vxe-column type="seq" align="center" title="#" width="50" />
                            <vxe-column field="kcbh" show-overflow width="150">
                                <template #header><vp-label zh="课程编号" en="Course No." /></template>
                                <template #default="scope">
                                    <span>{{ scope.row.kcbh }}</span>
                                </template>
                            </vxe-column>
                            <vxe-column field="kcmc" show-overflow>
                                <template #header><vp-label zh="课程名称" en="Couse Name" /></template>
                                <template #default="scope">
                                    <span>{{ scope.row.kcmc }}</span>
                                </template>
                            </vxe-column>
                            <vxe-column field="sfpx" width="150">
                                <template #header><vp-label zh="完成培训" en="Training Completion" /></template>
                                <template #default="scope">
                                    <span>{{ scope.row.sfpx ? "是/Yes" : scope.row.sfpx == 20 ? "否/No" : "" }}</span>
                                </template>
                            </vxe-column>
                            <vxe-column field="pgjg" min-width="150">
                                <template #header><vp-label zh="评估结果" en="Result" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`trainings[${scope.rowIndex}].pgjg`" label-width="auto" :rules="formPostApplys.pgjg">
                                        <el-radio-group v-model="scope.row.pgjg" v-if="type === 'training'">
                                            <el-radio :value="10">合格/Qualified</el-radio>
                                            <el-radio :value="20">不合格/Unqualified</el-radio>
                                        </el-radio-group>
                                        <span v-else>{{ scope.row.pgjg === 10 ? '合格/Qualified' : scope.row.pgjg === 20 ? '不合格/Unqualified' : '' }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="pgyj" min-width="150">
                                <template #header><vp-label zh="说明" en="Note" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`trainings[${scope.rowIndex}].pgyj`" label-width="auto">
                                        <el-input v-model="scope.row.pgyj" placeholder="请输入"  v-if="type === 'training'" />
                                        <span v-else>{{ scope.row.pgyj }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="attachments" min-width="150">
                                <template #header><vp-label zh="附件" en="Attachment" /></template>
                                <template #default="scope">
                                <RowAttachment :attachmentList="scope.row.attachments" :readOnly="type != 'training'"
                                    @attachmentListEmit="getAttachmentListEmit($event, scope.row)"></RowAttachment>
                                </template>
                            </vxe-column>
                        </vp-vxe-table>
                    </el-form-item>
                </vp-col>
            </el-row>
        </vp-card>
        <vp-card v-if="type === 'quality' || type === 'audit' || (type === 'view' && formData.qualifications.length && formData.qualifications[0].pgjg)">
            <template #header>
                <vp-label zh="资质审核" en="Qualification Verification" />
            </template>
            <el-row>
                <vp-col :span="1">
                    <el-form-item>
                        <template #label>
                            <div>
                                <div> <vp-label zh="岗位要求" en="Position Requirements" /> </div>
                                <div style="margin-top: 10px;">
                                    <vp-label zh="重新加载" en="Reload" style="cursor: pointer;" @click="loadQualificationList" v-if="type == 'quality'" />
                                </div>
                            </div>
                        </template>
                        <vp-vxe-table id="contactId" ref="tableRef" :data="formData.qualifications" row-key="id"
                            maxHeight="300" v-loading="loading2">
                            <vxe-column type="seq" align="center" title="#" width="50" />
                            <vxe-column field="kcid" show-overflow min-width="150">
                                <template #header><vp-label zh="岗位要求" en="Position Requirements" /></template>
                                <template #default="scope">
                                    <span>{{ scope.row.kcid }}</span>
                                </template>
                            </vxe-column>
                            <vxe-column field="pgjg" min-width="150">
                                <template #header><vp-label zh="评估结果" en="Result" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`qualifications[${scope.rowIndex}].pgjg`" label-width="auto" :rules="formPostApplys.pgjg">
                                        <el-radio-group v-model="scope.row.pgjg" v-if="type === 'quality'">
                                            <el-radio :value="10">合格/Qualified</el-radio>
                                            <el-radio :value="20">不合格/Unqualified</el-radio>
                                        </el-radio-group>
                                        <span v-else>{{ scope.row.pgjg === 10 ? '合格/Qualified' : scope.row.pgjg === 20 ? '不合格/Unqualified' : '' }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="pgyj" min-width="150">
                                <template #header><vp-label zh="说明" en="Note" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`qualifications[${scope.rowIndex}].pgyj`" label-width="auto">
                                        <el-input v-model="scope.row.pgyj" placeholder="请输入"  v-if="type === 'quality'" />
                                        <span v-else>{{ scope.row.pgyj }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="attachments" min-width="150">
                                <template #header><vp-label zh="附件" en="Attachment" /></template>
                                <template #default="scope">
                                <RowAttachment :attachmentList="scope.row.attachments" :readOnly="type != 'quality'"
                                    @attachmentListEmit="getAttachmentListEmit($event, scope.row)"></RowAttachment>
                                </template>
                            </vxe-column>
                        </vp-vxe-table>
                    </el-form-item>
                </vp-col>
            </el-row>
        </vp-card>
        <vp-card v-if="type === 'audit' || (type === 'view' && formData.yxqks)">
            <template #header>
                <vp-label zh="授权" en="Authorization" />
            </template>
            <el-row>
                <vp-col :span="4">
                    <el-form-item prop="yxqks">
                        <template #label><vp-label zh="授权开始" en="Authorization Start" align="left" /></template>
                        <el-date-picker v-if="type === 'audit'" @change="handleYxqksChange"
                        v-model="formData.yxqks" type="date" value-format="YYYY-MM-DD"></el-date-picker>
                        <span v-else>{{ formData.yxqks }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="yxqjz">
                        <template #label><vp-label zh="授权结束" en="Authorization End" align="left" /></template>
                        <el-date-picker v-if="type === 'audit'" 
                        v-model="formData.yxqjz" type="date" value-format="YYYY-MM-DD"></el-date-picker>
                        <span v-else>{{ formData.yxqjz }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
        </vp-card>
        <VpFileListCard :attachmentList="formData.attachments" @attachmentListEmit="getAttachmentListEmit($event, formData)"
            :readOnly="!(isEditPage)">
            <template #header>
                <vp-label zh="附件" en="Attachment" />
            </template>
        </VpFileListCard>

        <!-- 人员选择页面 -->
        <VpUserDialog ref="vpUserDialogRef"></VpUserDialog>
        <!-- 岗位选择 -->
        <VpPositionDialog ref="vpPositionDialogRef"></VpPositionDialog>
    </el-form>
</template>
<script setup lang="ts" name="examPostApply">
import { ref, defineAsyncComponent, computed, onMounted } from 'vue';
import validateUtils from '/@/utils/validateUtils';
import router from '/@/router';

import { useUserInfo } from '/@/stores/userInfo';
import { storeToRefs } from 'pinia';
const stores = useUserInfo();
const { userInfos } = storeToRefs(stores);

const VpCourseDialog = defineAsyncComponent(() => import('/@/components/vp/course/VpCourseDialog.vue'));
const VpUserDialog = defineAsyncComponent(() => import('/@/components/vp/user/VpUserDialog.vue'));
const VpPositionDialog = defineAsyncComponent(() => import('/@/components/vp/position/VpPositionDialog.vue'));
import VpAircraftTypeSelect from '/@/components/vp/aircraftType/VpAircraftTypeSelect.vue';
import VpFileListCard from '/@/components/vp/file/VpFileListCard.vue';
import RowAttachment from '/@/components/vp/file/VpRowAttachment.vue';
import { ElMessage } from "element-plus";
import request from '/@/utils/request';

const emits = defineEmits(['formSubmited']);
const props = defineProps({
    // 页面类型
	type: {
		type: String,
		default: 'add',
	},
	// 加载状态
	loading: {
		type: Boolean,
		default: false,
	},
	// 开启验证
	enableValid: {
		type: Boolean,
		default: true,
	},
});
const formData = ref({
    id:"",
    zt:10,
    bh:"",
    sqrdaid:"",
    sqrbh:"",
    sqrxm:"",
    sqrq:"",
    sqlx: 10,
    sqgwid:"",
    sqgwmc:"",
    sqgwbh:"",
    bz:"",
    fjglid:"",
    yxqks:"",
    yxqjz:"",
    trainings: [],
    qualifications: [],
    actypes: [],
    attachments: []
});
const formPostApplys = {
    sqrdaid:[ validateUtils.notNull ],
    sqrq:[ validateUtils.notNull ],
    sqlx:[ validateUtils.notNull ],
    sqgwid:[ validateUtils.notNull ],
    sqyy:[ validateUtils.notNull ],
    jx:[ validateUtils.notNull ],
    pgjg:[ validateUtils.notNull ],
}

const formPostApplys1 = {
    yxqks:[ validateUtils.notNull ],
    yxqjz:[ validateUtils.notNull ],
}
const loading1 = ref(false);
const loading2 = ref(false);


// 页面验证规则
const currentFormPostApplys = computed(() => {
    if (!props.enableValid) {
        return {};
    }

    if(props.type === 'add' || props.type === 'edit'){
        return formPostApplys
    }else if(props.type === 'audit'){
        return formPostApplys1
    }

    return {}
})

const formRef = ref();

// 是否是编辑页面
const isEditPage = computed(() => {
    return props.type === 'add' || props.type === 'edit';
});


// 清空数据
const initFormData = ()=>{
    formData.value = {
        id:"",
        zt:10,
        bh:"",
        sqrdaid:"",
        sqrbh:"",
        sqrxm:"",
        sqrq:"",
        sqlx: 10,
        sqgwid:"",
        sqgwmc:"",
        sqgwbh:"",
        bz:"",
        fjglid:"",
        yxqks:"",
        yxqjz:"",
        trainings: [],
        qualifications: [],
        actypes: [],
        attachments: []
    }
}

const loadTrainingList = ()=>{
    loading1.value = true;
    request.get('/quality/postApply/loadTrainingList', {
        params: {
            gwid: formData.value.sqgwid,
            sqrdaid: formData.value.sqrdaid,
            jxList: formData.value.actypes.map(item=>item.jx),
        }
    }).then(res => {
        formData.value.trainings = res.data;
    }).finally(() => {
        loading1.value = false;
    })
}

const loadQualificationList = ()=>{
    loading2.value = true;
    request.get(`/quality/postApply/loadQualificationList/${formData.value.sqgwid}`, {
    }).then(res => {
        formData.value.qualifications = res.data;
    }).finally(() => {
        loading2.value = false;
    })
}

/**
 * 获取数据
 */
 const getData = (zt:number): Promise<any>=>{
    let promise = new Promise((resolve, reject) => {
        let actypes = formData.value.actypes 
        if (actypes && actypes.length > 0) {
            const nameCounts:any = actypes.reduce((acc:any, item:any) => {
                const name = item.jx; 
                acc[name] = (acc[name] || 0) + 1;
                return acc;
            }, {});
            const duplicateNames = Object.keys(nameCounts).filter(
                (name) => nameCounts[name] > 1
            );
            if(duplicateNames.length){
                ElMessage.error('授权机型有重复的机型，请检查之后再提交')
                reject();
                return;
            }
        }
        if (zt === 10) {
            resolve({
                ...formData.value,
            });
            return;
        }
        formRef.value.validate((valid: boolean) => {
            const data = {
                ...formData.value,
            };
            if (valid) {
                resolve(data);
            } else {
                reject();
            }
        })
    })
    return promise;
}

// 回显数据
const setData = (data: any) => {
    initFormData();
    formData.value = {
        ...formData.value,
        ...data,
    };
    formData.value.trainings = formData.value.trainings??[];
    formData.value.qualifications = formData.value.qualifications??[];
    if (props.type === 'add') {
        //获取当前登录人
        formData.value.sqrdaid = userInfos.value.user.rydaid;
        formData.value.sqrbh = userInfos.value.user.rydabh;
        formData.value.sqrxm = userInfos.value.user.realname;
        //获取当前日期 年-月-日
        const currentDate = new Date();
        formData.value.sqrq = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')}`;
    }else if(props.type === 'audit'){
        //获取当前日期 年-月-日
        const currentDate = new Date();
        formData.value.yxqks = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${(currentDate.getDate() + 1).toString().padStart(2, '0')}`;
        formData.value.yxqjz = `${currentDate.getFullYear()+2}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${(currentDate.getDate() + 1).toString().padStart(2, '0')}`;
    }
}

// 选择培训人员
const vpUserDialogRef = ref();
const handleChooseTrainer = ()=>{
    vpUserDialogRef.value.handleOpen({
        type: 2, // 1、选择人员t_user 2、选择档案b_p3_001
        multi: false,    // 是否多选
        selected:  formData.value.sqrdaid, // 默认选中人员id
        callback: (data: any) => {
            formData.value.sqrdaid = data.daid
            formData.value.sqrxm = data.xm
            formData.value.sqrbh = data.dabh
        }
    });
}

const vpPositionDialogRef = ref()
const handleChoosePosition = () =>{
  vpPositionDialogRef.value.handleOpen({
    selected: formData.value.sqgwid,
    callback: (data: any) => {
        console.log(data, 9966);
        formData.value.sqgwid = data.id;
        formData.value.sqgwmc = data.mc;
        formData.value.sqgwbh = data.bh;
    }
  })
}

const getAttachmentListEmit = (list: any, row: any) => {
  row.attachments = list;
}

const handlePersonnelFileClick = () => {
	router.push({
		name: "viewTrainingPersonnelFile",
		params: {
			id: formData.value.sqrdaid,
		},
	})
}

const handleAddAcType = () => {
    formData.value.actypes.push({
        id: "",
        mainid: "",
        jx: "",
        lb: "",
    });
}
const handleDeleteAcType = (index: number) => {
    formData.value.actypes.splice(index, 1);
}

const handleYxqksChange = () => {
    let date = Number(formData.value.yxqks.substring(0, 4))
    formData.value.yxqjz = (date + 2) + formData.value.yxqks.substring(4, 10)
}



defineExpose({
    setData,
    getData,
    loadTrainingList
})

</script>
<style scoped lang="scss">
</style>